package com.putao.utils;

import com.putao.error.BusinessException;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;



/**
 * @author fuhehuang
 * @email 2628279194@qq.com
 */
public class ReflexUtil {

    /**
     * 通过反射拿到对象中指定属性值
     * @param t 对象
     * @param column 属性 驼峰式
     * @param <T> 放心
     * @return
     */
    public static <T> Object getValueByName(T t, String column) {
        Class<?> aClass = t.getClass();
        try {
            Field field = aClass.getDeclaredField(column);
            field.setAccessible(true);
            return field.get(t);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 根据传来的属性依次判断对象中是否存在该值
     * @param t 对象
     * @param columnList 属性集合 驼峰式
     * @param <T>
     * @return
     */
    public static <T> List<T> checkValueByNameList(T t, List<String> columnList) {
        Class<?> aClass = t.getClass();
        // 获取类中声明的字段
        Field[] fields = aClass.getDeclaredFields();
        if (fields.length > 0) {
            Map<String, Field> fieldNameMap = Arrays.stream(fields).collect(Collectors.toMap(Field::getName, Function.identity(), (front, behind) -> front));
            for (String column : columnList) {
                Field field = fieldNameMap.get(column);
                // 避免 can not access a member of class com.java.test.Person with modifiers "private"
                field.setAccessible(true);
                try {
                    AssertUtil.hasText(field.get(t) + "", "字典项文本不能为空");
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        }
        return null;
    }

    /**
     * 判断对象(本类的属性，不包含父类)是否为空，有一个属性不为空，返回false,反之返回true
     * @param t
     * @return
     * @param <T>
     */
    public static <T> boolean checkEmpty(T t, List<String> ignoreColumnList) throws Exception {
        if (null == t) return true;
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (ignoreColumnList.contains(field.getName())) {
                continue;
            }
            if (null != field.get(t)) {
                return false;
            }
        }
        return true;
    }
}
